import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useCartStore } from './cartStore'
import { loginAPI, getUserInfoAPI } from '@/api/user'
import { mergeCartAPI } from '@/api/cart'
import { setToken, removeToken, getToken } from '@/utils/auth'
import { useRouter } from 'vue-router'
export const useUserStore = defineStore(
  'user',
  () => {
    const cartStore = useCartStore()
    const router = useRouter()
    // 1. 定义管理用户数据的 state
    const userInfo = ref({})
    // 2. 定义获取接口数据的 action 函数
    const getUserInfo = async ({ username, password }) => {
      const { data: res } = await loginAPI({ username, password })
      console.log(res)
      if (res.code === 200) {
        console.log('登录成功')
        setToken('token', res.data)
        checkLogin()
        router.push('/')
      }
      // 合并购物车的操作
      // await mergeCartAPI(cartStore.cartList.map(item =>{
      //     return {
      //         skuId: item.skuId,
      //         selected: item.selected,
      //         count: item.count
      //     }
      // }))
      // cartStore.updateNewList()
    }

    const checkLogin = async () => {
      const { data: res } = await getUserInfoAPI()
      userInfo.value = res.data
    }

    // 退出时清除用户信息
    const clearUserInfo = () => {
      userInfo.value = {}
      // 执行清除购物车的 action
      cartStore.clearCart()
    }
    return {
      userInfo,
      getUserInfo,
      clearUserInfo,
    }
  },
  {
    persist: true, // 开启本地存储
  }
)
